import jwt
import datetime


class JwtToken(object):
    _salt = "al123@*Jkflsjdljfdlkj#$**&(LLLJL#J$5441js"
    _expire_message = dict(code=404, msg="token已失效!")
    _unknown_error_message = dict(code=404, msg="请重新登录！")
    # jwt过期时间，以天为单位
    expire_time = 100

    # 生成jwt
    def generate_token(self, openid: str):
        payload = {
            "exp": datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(self.expire_time),
            "iat": datetime.datetime.now(datetime.timezone.utc),
            # 签发人
            "iss": "admin",
            'openid': openid,
        }
        headers = dict(typ="jwt", alg="HS256")
        result = jwt.encode(payload, self._salt, algorithm='HS256', headers=headers)
        return result

    # 解析jwt
    def parse_token(self, temp_token: str):
        verify_status = False
        try:
            payload_data = jwt.decode(temp_token, self._salt, algorithms=['HS256'])
            verify_status = True
        except jwt.ExpiredSignatureError:
            payload_data = self._expire_message
        except Exception as e:
            payload_data = self._unknown_error_message
            print(f"解析token错误：{e}")
        return payload_data, verify_status


jwt_tools = JwtToken()


# 测试代码
if __name__ == '__main__':
    # 创建一个JwtToken实例
    jwt_tools = JwtToken()

    # 1. 生成一个JWT令牌
    openid = "openid"
    token = jwt_tools.generate_token(openid)
    print("生成的令牌：", token)

    # 2. 解析并验证生成的令牌
    parsed_data, is_valid = jwt_tools.parse_token(token)
    print("解析后的数据：", parsed_data)
    print("令牌是否有效：", is_valid)
